﻿using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace PostgreSQL.Convert;

public class TypeConvert(TypeCodeEntity tcode) : BaseConvert
{
    private readonly TypeCodeEntity TCode = tcode;

    protected override List<string> Run()
    {
        if (TCode.Type.StartsWith("VARRAY"))
        {
            var len = Regex.Match(TCode.Type,"[0-9]+").Value;
            TypeConvertor.AddNew(TCode.Name!, $"{TCode.OfType}[{len}]");
            return [];
        }
        else if (TCode.Type.Equals("TABLE"))
        {
            TypeConvertor.AddNew(TCode.Name!, $"{TCode.OfType}[]");
            return [];
        }
        var list = new List<string>()
        {
            $"CREATE TYPE {TCode.Name}("
        };
        foreach (var obj in TCode.Objects)
        {
            list.Add($"{obj.SqlLine()},");
        }
        list[^1] = list[^1][..^1];
        list.Add(")");
        return list;
    }
}
